<template>
  <div>
    <el-dialog :visible.sync="dialogAdd.show" title="添加小区信息" :append-to-body="true" :modal="true">
      <el-form v-bind:model="community" ref="communityForm" :rules="rules" label-width="100px">
        <el-form-item label="类型" prop="type">
          <template>
            <el-select v-model="community.type" filterable placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in communityTagList"
                :key="item.id"
                :label="item.tagType"
                :value="item.tagType">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="community.name"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input placeholder="输入地址" v-model="community.address" id="suggestId"></el-input>
          <div id="searchResultPanel"
               style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;z-index:99999;position:absolute;"></div>
          <baidu-map :center="center" :zoom="zoom" @ready="mapReady" style="padding-left: 10px"></baidu-map>
        </el-form-item>
        <el-form-item label="所在商圈" prop="tradeArea">
          <template>
            <el-select value-key="id" v-model="tradeArea" filterable placeholder="请选择" @change="tradeAreaChange"
                       style="width: 100%">
              <el-option
                v-for="item in tradeAreas"
                :key="item.id"
                :label="item.tradeAreaName"
                :value="item">
              </el-option>
            </el-select>
          </template>
        </el-form-item>

      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="handleCancel('communityForm')">取 消</el-button>
        <el-button @click="addCommunityForm('communityForm')" type="primary">确 定</el-button>
        <el-button @click="resetForm('communityForm')" type="primary">重 置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tradeAreaApi from '@/api/system/tradeArea'
import communityTagApi from '@/api/community/communityTag'
import communityApi from '@/api/community/community'

export default {
  name: 'addCommunity',
  props: {
    dialogAdd: Object
  },
  options: [],
  data () {
    return {
      center: {lng: 0, lat: 0}, // 地图中的中心位置
      zoom: 3, // 表地图中的区域范围
      tradeAreas: [], // 表示商圈列表
      tradeArea: {}, // 表示小区添加中的商圈
      communityTagList: [], // 小区标签列表
      community: { // 输入提交单中的小区
        id: '', // 小区id
        type: '', // 小区所属的类型
        name: '', // 小区名称
        address: '', // 小区地址
        districtId: '', // 小区的所在省市区id
        tradeAreaId: '', // 小区所在商圈id
        tradeArea: '', // 小区所在商圈名称
        longitude: '', // 小区具体的经度
        latitude: ''// 小区具体的纬度
      },
      address: '', // 地址输入框中的地址
      rules: {// 提交表单填写规则
        type: [{required: true, message: '类型不能为空', trigger: 'blur'}],
        name: [{required: true, message: '名字不能为空', trigger: 'blur'}],
        address: [{required: true, message: '地址不能为空', trigger: 'blur'}],
        tradeAreas: [{required: true, message: '商圈不能为空', trigger: 'blur'}]
      }
    }
  },
  methods: {
    /**
     * @description 取消填写添加小区表单
     * @param formName
     */
    handleCancel (formName) {
      this.resetForm(formName)
      this.tradeArea = null
      this.dialogAdd.show = false
    },
    /**
     * @description 重置清空表单内容
     * @param formName
     */
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.tradeArea = null
    },
    /**
     * @description 数据赋值
     */
    tradeAreaChange () {
      this.community.districtId = this.tradeArea.prefecture
      this.community.tradeArea = this.tradeArea.tradeAreaName
      this.community.tradeAreaId = this.tradeArea.id
    },
    /**
     * @description 地图初始化信息赋值
     * @param BMap
     * @param map
     */
    mapReady ({BMap, map}) {
      let _that = this
      console.log(BMap, map)
      this.BMap = BMap
      this.map = map
      this.center.lng = 116.404
      this.center.lat = 39.915
      this.zoom = 15

      function G (id) {
        return document.getElementById(id)
      }

      map.centerAndZoom('北京', 12) // 初始化地图,设置城市和地图级别。

      var ac = new BMap.Autocomplete( // 建立一个自动完成的对象
        {
          'input': 'suggestId',
          'location': map
        })
      /**
       * @description 鼠标放在下拉列表上的事件
       */
      ac.addEventListener('onhighlight', function (e) {
        var str = ''
        var _value = e.fromitem.value
        var value = ''
        if (e.fromitem.index > -1) {
          value = _value.province + _value.city + _value.district + _value.street + _value.business
        }
        str = 'FromItem<br />index = ' + e.fromitem.index + '<br />value = ' + value

        value = ''
        if (e.toitem.index > -1) {
          _value = e.toitem.value
          value = _value.province + _value.city + _value.district + _value.street + _value.business
        }
        str += '<br />ToItem<br />index = ' + e.toitem.index + '<br />value = ' + value
        G('searchResultPanel').innerHTML = str
      })

      var myValue
      ac.addEventListener('onconfirm', function (e) { // 鼠标点击下拉列表后的事件
        var _value = e.item.value
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business
        G('searchResultPanel').innerHTML = 'onconfirm<br />index = ' + e.item.index + '<br />myValue = ' + myValue
        setPlace()
        _that.community.address = myValue
        var geoc = new BMap.Geocoder()
        geoc.getPoint(myValue, function (point) {
          if (point) {
            _that.community.latitude = point.lat
            _that.community.longitude = point.lng
          } else {
            alert('您选择地址没有解析到结果!')
          }
        }, '北京市')
      })

      function setPlace () {
        map.clearOverlays() // 清除地图上所有覆盖物
        function myFun () {
          var pp = local.getResults().getPoi(0).point // 获取第一个智能搜索的结果
          map.centerAndZoom(pp, 18)
          map.addOverlay(new BMap.Marker(pp)) // 添加标注
        }

        var local = new BMap.LocalSearch(map, { // 智能搜索
          onSearchComplete: myFun
        })
        local.search(myValue)
      }

      map.addEventListener('click', function (e) {
        alert(e.point.lng + ', ' + e.point.lat)
      })
    },
    /**
     * @description 添加小区按钮事件
     * @param formAdd
     */
    addCommunityForm (formAdd) {
      let _that = this
      _that.$refs[formAdd].validate((valid) => {
        if (valid) {
          communityApi.addCommunityForm(_that.community).then(res => {
            _that.$message({
              type: 'success',
              message: '添加成功'
            })
            _that.$refs[formAdd].resetFields()
            _that.tradeArea = null
            _that.dialogAdd.show = false
            _that.$emit('update')
          }
          )
        } else {
          return false
        }
      })
    },
    /**
     * @description 得到商圈列表,用户添加小区的商圈选择
     */
    getTradeAreaList () {
      tradeAreaApi.getTradeAreaList().then(data => {
        this.tradeAreas = data.data
      })
    },
    /**
     * @description 得到小区标签列表,用户添加小区时的标签选择
     */
    getCommunityTagList () {
      communityTagApi.getCommunityTagList().then(data => {
        this.communityTagList = data.data
      })
    }
  },
  /**
   * @description 页面初始化时,可以需要在选择框初始化小区标签列表和商圈列表
   */
  created () {
    this.getTradeAreaList()
    this.getCommunityTagList()
  }
}
</script>

<style>
.tangram-suggestion-main {
  z-index: 9999;
}

#tangram-suggestion--TANGRAM__1q-main {
  z-index: 9999;
}
</style>
